﻿package org.dong.common.security;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.dong.common.utils.Context;
import org.dong.sys.entity.User;
import org.dong.sys.service.SystemService;

public class AuthRealm extends AuthorizingRealm{

	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		//用户名
		 String currentUsername = (String)super.getAvailablePrincipal(principals);  
		//权限信息
		 SimpleAuthorizationInfo simpleAuthorInfo = new SimpleAuthorizationInfo();  
		 
		 if("liuxiaodong".equals(currentUsername)){
			 simpleAuthorInfo.addRole("user");
			 simpleAuthorInfo.addStringPermission("user:layout");
			 simpleAuthorInfo.addStringPermission("layout:view");
		 }
		return simpleAuthorInfo;
	}

	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authToken) throws AuthenticationException {
			UsernamePasswordToken token = (UsernamePasswordToken)authToken;  
			
			//登录名
			String username=token.getUsername();
			String password=new String(token.getPassword());
			SystemService sysService=Context.getBean(SystemService.class);
			User user=sysService.loginAuth(new User(username, password));
			if(user!=null){
				//认证info
				AuthenticationInfo authcInfo = new SimpleAuthenticationInfo(username, password, this.getName());
				return authcInfo;
			}else{
				return null;
			}
	}
}
